package top.ajun.mall.product.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.ajun.common.utils.R;
import top.ajun.mall.product.entity.CategoryEntity;
import top.ajun.mall.product.service.CategoryService;

import java.util.Arrays;
import java.util.List;

/**
 * 商品三级分类
 *
 * @author AJun
 * @email 1241088536@qq.com
 * @date 2020-11-24 22:00:40
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有商品分类以及其子分类，以树形结构组装
     */
    @RequestMapping("/list/tree")
    public R list() {
        List<CategoryEntity> categories = categoryService.listWithTree();
        return R.ok().put("data", categories);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId) {
        CategoryEntity category = categoryService.getById(catId);
        return R.ok().put("data", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CategoryEntity category) {
        categoryService.save(category);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody CategoryEntity category) {
        categoryService.updateDetail(category);
        return R.ok();
    }

    /**
     * 批量修改分类及其子分类的排序
     */
    @RequestMapping("/update/sort")
    public R updateSort(@RequestBody CategoryEntity[] categories) {
        categoryService.updateBatchById(Arrays.asList(categories.clone()));
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds) {
        // TODO 检查当前要删除的菜单是否被别的地方引用
        categoryService.removeMenuByIds(Arrays.asList(catIds.clone()));
        return R.ok();
    }

}
